{{define "content"}}
<div x-data="pushRecordsData()" class="space-y-6">
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">推送记录</h1>
            <p class="mt-1 text-sm text-gray-500">查看和管理所有推送记录，支持重试失败的推送。</p>
        </div>
        <div class="mt-4 sm:mt-0 flex space-x-3">
            <a href="/push" 
               class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
                <i class="fas fa-arrow-left mr-2"></i>
                返回推送管理
            </a>
            <button @click="refreshRecords()" 
                    :disabled="loading"
                    class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50">
                <i class="fas fa-sync-alt mr-2" :class="loading ? 'animate-spin' : ''"></i>
                刷新
            </button>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">筛选条件</h3>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Customer Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">客户</label>
                    <input type="text" 
                           x-model="filters.customer"
                           @input="applyFilters()"
                           placeholder="客户姓名或手机号"
                           class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                
                <!-- Partner Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">合作机构</label>
                    <input type="text" 
                           x-model="filters.partner"
                           @input="applyFilters()"
                           placeholder="机构名称"
                           class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                
                <!-- Push Type Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">推送类型</label>
                    <select x-model="filters.pushType" @change="applyFilters()" 
                            class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        <option value="">全部类型</option>
                        <option value="manual">手动推送</option>
                    </select>
                </div>
                
                <!-- Status Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">推送状态</label>
                    <select x-model="filters.status" @change="applyFilters()" 
                            class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        <option value="">全部状态</option>
                        <option value="pending">待处理</option>
                        <option value="success">成功</option>
                        <option value="failed">失败</option>
                    </select>
                </div>
            </div>
            
            <!-- Date Range Filter -->
            <div class="mt-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
                        <input type="date" 
                               x-model="filters.startDate"
                               @change="applyFilters()"
                               class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
                        <input type="date" 
                               x-model="filters.endDate"
                               @change="applyFilters()"
                               class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
            </div>
            
            <!-- Clear Filters -->
            <div class="mt-4 flex justify-end">
                <button @click="clearFilters()" 
                        class="text-sm text-gray-600 hover:text-gray-800">
                    清空筛选条件
                </button>
            </div>
        </div>
    </div>

    <!-- Records Table -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">推送记录</h3>
                <div class="text-sm text-gray-500">
                    共 <span x-text="pagination.total"></span> 条记录
                </div>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户信息</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">合作机构</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">推送类型</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">推送时间</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <template x-for="record in records" :key="record.id">
                        <tr class="hover:bg-gray-50">
                            <!-- Customer Info -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div>
                                        <div class="text-sm font-medium text-gray-900" x-text="record.customer?.name || '-'"></div>
                                        <div class="text-sm text-gray-500">
                                            <span x-text="record.customer?.phone || '-'"></span> • 
                                            <span x-text="record.customer?.city || '-'"></span> • 
                                            <span x-text="record.customer?.subject || '-'"></span>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Partner Info -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div>
                                    <div class="text-sm font-medium text-gray-900" x-text="record.partner?.name || '-'"></div>
                                    <div class="text-sm text-gray-500">
                                        <span x-text="record.partner?.city || '-'"></span> • 
                                        <span x-text="record.partner?.contact_person || '-'"></span>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Push Type -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                      :class="{
                                          'bg-green-100 text-green-800': record.push_type === 'manual'
                                      }"
                                      x-text="{
                                          'manual': '手动推送'
                                      }[record.push_type] || record.push_type"></span>
                            </td>
                            
                            <!-- Status -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                      :class="{
                                          'bg-yellow-100 text-yellow-800': record.status === 'pending',
                                          'bg-green-100 text-green-800': record.status === 'success',
                                          'bg-red-100 text-red-800': record.status === 'failed'
                                      }"
                                      x-text="{
                                          'pending': '待处理',
                                          'success': '成功',
                                          'failed': '失败'
                                      }[record.status] || record.status"></span>
                            </td>
                            
                            <!-- Push Time -->
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <div x-text="formatDateTime(record.created_at)"></div>
                                <div class="text-xs text-gray-400" x-show="record.updated_at !== record.created_at">
                                    更新: <span x-text="formatDateTime(record.updated_at)"></span>
                                </div>
                            </td>
                            
                            <!-- Actions -->
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <div class="flex items-center space-x-2">
                                    <button @click="viewRecord(record)" 
                                            class="text-blue-600 hover:text-blue-900">
                                        查看
                                    </button>
                                    <button @click="retryPush(record)" 
                                            x-show="record.status === 'failed'"
                                            :disabled="retrying"
                                            class="text-green-600 hover:text-green-900 disabled:opacity-50">
                                        重试
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
            
            <!-- Empty State -->
            <div class="text-center py-12" x-show="records.length === 0 && !loading">
                <i class="fas fa-clipboard-list text-4xl text-gray-400 mb-4"></i>
                <h4 class="text-lg font-medium text-gray-900 mb-2">暂无推送记录</h4>
                <p class="text-gray-500 mb-4">还没有任何推送记录，开始您的第一次推送吧</p>
                <a href="/push/manual" class="text-blue-600 hover:text-blue-800 font-medium">
                    开始手动推送 →
                </a>
            </div>
            
            <!-- Loading State -->
            <div class="text-center py-12" x-show="loading">
                <i class="fas fa-spinner fa-spin text-4xl text-gray-400 mb-4"></i>
                <p class="text-gray-500">正在加载推送记录...</p>
            </div>
        </div>
        
        <!-- Pagination -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6" x-show="records.length > 0">
            <div class="flex-1 flex justify-between sm:hidden">
                <button @click="previousPage()" 
                        :disabled="pagination.page <= 1"
                        class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    上一页
                </button>
                <button @click="nextPage()" 
                        :disabled="pagination.page >= pagination.totalPages"
                        class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    下一页
                </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示第 <span x-text="(pagination.page - 1) * pagination.size + 1"></span> 到 
                        <span x-text="Math.min(pagination.page * pagination.size, pagination.total)"></span> 条，
                        共 <span x-text="pagination.total"></span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        <button @click="previousPage()" 
                                :disabled="pagination.page <= 1"
                                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        
                        <template x-for="page in getPageNumbers()" :key="page">
                            <button @click="goToPage(page)" 
                                    :class="page === pagination.page ? 'bg-blue-50 border-blue-500 text-blue-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'"
                                    class="relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                                <span x-text="page"></span>
                            </button>
                        </template>
                        
                        <button @click="nextPage()" 
                                :disabled="pagination.page >= pagination.totalPages"
                                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Record Detail Modal -->
    <div x-show="showDetailModal" 
         x-transition:enter="ease-out duration-300" 
         x-transition:enter-start="opacity-0" 
         x-transition:enter-end="opacity-100" 
         x-transition:leave="ease-in duration-200" 
         x-transition:leave-start="opacity-100" 
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" 
         style="display: none;">
        <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
            <div class="mt-3" x-show="selectedRecord">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">推送记录详情</h3>
                    <button @click="closeDetailModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="space-y-6">
                    <!-- Basic Info -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-sm font-medium text-gray-900 mb-3">客户信息</h4>
                            <div class="bg-gray-50 rounded-lg p-4 space-y-2">
                                <div class="text-sm">
                                    <span class="text-gray-500">姓名:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.customer?.name || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">手机:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.customer?.phone || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">城市:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.customer?.city || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">学科:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.customer?.subject || '-'"></span>
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <h4 class="text-sm font-medium text-gray-900 mb-3">合作机构</h4>
                            <div class="bg-gray-50 rounded-lg p-4 space-y-2">
                                <div class="text-sm">
                                    <span class="text-gray-500">机构名称:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.partner?.name || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">城市:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.partner?.city || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">联系人:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.partner?.contact_person || '-'"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">联系电话:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.partner?.contact_phone || '-'"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Push Details -->
                    <div>
                        <h4 class="text-sm font-medium text-gray-900 mb-3">推送详情</h4>
                        <div class="bg-gray-50 rounded-lg p-4 space-y-3">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div class="text-sm">
                                    <span class="text-gray-500">推送类型:</span>
                                    <span class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                          :class="{
                                              'bg-blue-100 text-blue-800': selectedRecord?.push_type === 'smart',
                                              'bg-green-100 text-green-800': selectedRecord?.push_type === 'manual',
                                              'bg-purple-100 text-purple-800': selectedRecord?.push_type === 'batch'
                                          }"
                                          x-text="{
                                              'manual': '手动推送'
                                          }[selectedRecord?.push_type] || selectedRecord?.push_type"></span>
                                </div>
                                <div class="text-sm">
                                    <span class="text-gray-500">推送状态:</span>
                                    <span class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                          :class="{
                                              'bg-yellow-100 text-yellow-800': selectedRecord?.status === 'pending',
                                              'bg-green-100 text-green-800': selectedRecord?.status === 'success',
                                              'bg-red-100 text-red-800': selectedRecord?.status === 'failed'
                                          }"
                                          x-text="{
                                              'pending': '待处理',
                                              'success': '成功',
                                              'failed': '失败'
                                          }[selectedRecord?.status] || selectedRecord?.status"></span>
                                </div>
                                <div class="text-sm" x-show="selectedRecord?.match_score">
                                    <span class="text-gray-500">匹配度:</span>
                                    <span class="ml-2 text-gray-900" x-text="selectedRecord?.match_score + '%'"></span>
                                </div>
                            </div>
                            
                            <div class="text-sm">
                                <span class="text-gray-500">推送时间:</span>
                                <span class="ml-2 text-gray-900" x-text="formatDateTime(selectedRecord?.created_at)"></span>
                            </div>
                            
                            <div class="text-sm" x-show="selectedRecord?.updated_at !== selectedRecord?.created_at">
                                <span class="text-gray-500">更新时间:</span>
                                <span class="ml-2 text-gray-900" x-text="formatDateTime(selectedRecord?.updated_at)"></span>
                            </div>
                            
                            <div class="text-sm" x-show="selectedRecord?.notes">
                                <span class="text-gray-500">备注:</span>
                                <div class="mt-1 text-gray-900" x-text="selectedRecord?.notes"></div>
                            </div>
                            
                            <div class="text-sm" x-show="selectedRecord?.error_message">
                                <span class="text-gray-500">错误信息:</span>
                                <div class="mt-1 text-red-600" x-text="selectedRecord?.error_message"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-6 flex justify-end space-x-3">
                    <button @click="retryPush(selectedRecord)" 
                            x-show="selectedRecord?.status === 'failed'"
                            :disabled="retrying"
                            class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50">
                        <i class="fas fa-redo mr-2" :class="retrying ? 'animate-spin' : ''"></i>
                        重试推送
                    </button>
                    <button @click="closeDetailModal()" 
                            class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        关闭
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function pushRecordsData() {
        return {
            loading: false,
            retrying: false,
            showDetailModal: false,
            selectedRecord: null,
            records: [],
            
            filters: {
                customer: '',
                partner: '',
                pushType: '',
                status: '',
                startDate: '',
                endDate: ''
            },
            
            pagination: {
                page: 1,
                size: 20,
                total: 0,
                totalPages: 0
            },
            
            init() {
                this.loadRecords();
            },
            
            async loadRecords() {
                this.loading = true;
                try {
                    const params = new URLSearchParams({
                        page: this.pagination.page,
                        size: this.pagination.size,
                        ...this.filters
                    });
                    
                    // 移除空值
                    for (const [key, value] of params.entries()) {
                        if (!value) {
                            params.delete(key);
                        }
                    }
                    
                    const response = await fetch(`/api/v1/push/records?${params.toString()}`, {
                        method: 'GET',
                        credentials: 'include',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            this.records = data.data || [];
                            this.pagination.total = data.total || 0;
                            this.pagination.page = data.page || 1;
                            this.pagination.size = data.size || 20;
                            this.pagination.totalPages = Math.ceil(this.pagination.total / this.pagination.size);
                        } else {
                            console.error('API Error:', data.message);
                            showToast(data.message || '加载推送记录失败', 'error');
                        }
                    } else {
                        console.error('HTTP Error:', response.status, response.statusText);
                        showToast('加载推送记录失败', 'error');
                    }
                } catch (error) {
                    console.error('Failed to load push records:', error);
                    showToast('加载推送记录失败', 'error');
                } finally {
                    this.loading = false;
                }
            },
            
            applyFilters() {
                this.pagination.page = 1;
                this.loadRecords();
            },
            
            clearFilters() {
                this.filters = {
                    customer: '',
                    partner: '',
                    pushType: '',
                    status: '',
                    startDate: '',
                    endDate: ''
                };
                this.applyFilters();
            },
            
            refreshRecords() {
                this.loadRecords();
            },
            
            previousPage() {
                if (this.pagination.page > 1) {
                    this.pagination.page--;
                    this.loadRecords();
                }
            },
            
            nextPage() {
                if (this.pagination.page < this.pagination.totalPages) {
                    this.pagination.page++;
                    this.loadRecords();
                }
            },
            
            goToPage(page) {
                this.pagination.page = page;
                this.loadRecords();
            },
            
            getPageNumbers() {
                const pages = [];
                const current = this.pagination.page;
                const total = this.pagination.totalPages;
                
                if (total <= 7) {
                    for (let i = 1; i <= total; i++) {
                        pages.push(i);
                    }
                } else {
                    if (current <= 4) {
                        for (let i = 1; i <= 5; i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(total);
                    } else if (current >= total - 3) {
                        pages.push(1);
                        pages.push('...');
                        for (let i = total - 4; i <= total; i++) {
                            pages.push(i);
                        }
                    } else {
                        pages.push(1);
                        pages.push('...');
                        for (let i = current - 1; i <= current + 1; i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(total);
                    }
                }
                
                return pages.filter(page => page !== '...');
            },
            
            viewRecord(record) {
                this.selectedRecord = record;
                this.showDetailModal = true;
            },
            
            closeDetailModal() {
                this.showDetailModal = false;
                this.selectedRecord = null;
            },
            
            async retryPush(record) {
                if (!record || record.status !== 'failed') return;
                
                this.retrying = true;
                try {
                    const response = await fetch(`/api/v1/push/retry/${record.id}`, {
                        method: 'POST',
                        credentials: 'include',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            showToast('重试推送成功', 'success');
                            this.loadRecords();
                            if (this.showDetailModal) {
                                this.closeDetailModal();
                            }
                        } else {
                            showToast(data.message || '重试推送失败', 'error');
                        }
                    } else {
                        showToast('重试推送失败', 'error');
                    }
                } catch (error) {
                    console.error('Retry push failed:', error);
                    showToast('重试推送失败', 'error');
                } finally {
                    this.retrying = false;
                }
            },
            
            formatDateTime(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
        }
    }
</script>
{{end}}